package com.teng.mylibrary.net

import androidx.lifecycle.LifecycleOwner
import com.uber.autodispose.AutoDispose
import com.uber.autodispose.AutoDisposeConverter
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers

/**
 * Description:    rxjava绑定生命周期
 * Author:         liuteng
 * CreateDate:     2021年12月3日
 * UpdateRemark:   更新说明
 */
object RxUtil {
    /**
     * 线程调度器
     */
    fun <T> schedulersTransformer(): ObservableTransformer<T, T> {
        return ObservableTransformer<T, T> { upstream ->
            upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
        }
    }

    fun <T> bindLifecycle(lifecycleOwner: LifecycleOwner): AutoDisposeConverter<T> {
        return AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOwner))
    }


    fun <T> exceptionTransformer(): ObservableTransformer<T, T> {
        return ObservableTransformer<T, T> { upstream ->
            upstream.onErrorResumeNext(HttpResponseFunc<T>()) //                        .map(new HandleFuc<T>())  //这里可以取出BaseResponse中的Result
        }
    }

    private class HttpResponseFunc<T> :
        Function<Throwable?, Observable<T>> {

        override fun apply(t: Throwable): Observable<T> {
            return Observable.error(ExceptionHandle.handleException(t))
        }
    }

}